import type { CSSProperties } from 'react'
import { Select } from 'antd'
import { useGetModalInfo } from './index'
const { OptGroup, Option } = Select;
interface IFilds {
  AttrType: string
  DefaultVal: null | string
  Describe: string
  Display: boolean
  IsCustomized: boolean
  IsGenerated: boolean
  IsNull: boolean
  Key: string
  Length: number
  Name: string
  Primary: boolean
  PublishState: number
  Scale: number
  System: boolean
  Type: string
  Unique: boolean
}

interface IModelType {
  Describe: string | null
  ModelKey: string
  ModelType: number
  ModuleId: string
  Name: string
}


type FieldsData = IModelType & {
  Fields: IFilds[]
}


export interface IFieldValue {
  name: string;
  type: string
  key: string
}
interface IgetFilds {
  modelFields?: FieldsData[];
  value: IFieldValue;
  datakey: string;
  style?: CSSProperties;
  onChange: (val: {
    [key: string]: {
      name: string;
      type: string
      key: string
    }
  }) => void;
}

/**
 * 获取模型组件
 * **/
export const GetFilds = (props: IgetFilds) => {

  const fields = useGetModalInfo();
  const modelFields = props.modelFields ?? fields;

  function handleChange(value: string) {
    const data = value?.split?.('|');
    if (data?.length > 1) {
      const model = modelFields.find((item) => item.ModelKey == data[0]);
      const fieldData = model?.Fields.find((item) => item.Key == data[1]);
      props.onChange({
        [props.datakey]: {
          key: `${model?.ModelKey}|${fieldData?.Key}`,
          name: fieldData?.Name ?? '',
          type: fieldData?.Type ?? ''
        }
      })
    }
  }

  return (
    <Select
      placeholder={'请选择'}
      style={{
        minWidth: 150,
        ...props.style
      }}
      value={props.value?.key ?? ''}
      allowClear
      onClear={() => {
        props.onChange({
          [props.datakey]: null
        })
      }}
      onChange={handleChange}>
      {
        modelFields.map((item: FieldsData) => {
          return (<OptGroup label={item.Name}>
            {
              item.Fields.map((item2: IFilds) => {
                return <Option key={item2.Key} value={`${item.ModelKey}|${item2.Key}`}>{item2.Name}</Option>
              })
            }
          </OptGroup>)
        })
      }
    </Select>
  )
}
